/*
 * 
 * 
 * 
 */
package com.hboxs.asl.service.impl;

import com.hboxs.asl.Page;
import com.hboxs.asl.Pageable;
import com.hboxs.asl.dao.CouponDao;
import com.hboxs.asl.entity.Coupon;
import com.hboxs.asl.entity.CouponCode;
import com.hboxs.asl.entity.Member;
import com.hboxs.asl.service.CouponService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * Service - 优惠券
 */
@Service("couponServiceImpl")
public class CouponServiceImpl extends BaseServiceImpl<Coupon, Long> implements CouponService {

    @Resource(name = "couponDaoImpl")
    private CouponDao couponDao;

    @Resource(name = "couponDaoImpl")
    public void setBaseDao(CouponDao couponDao) {
        super.setBaseDao(couponDao);
    }

    @Transactional(readOnly = true)
    public Page<Coupon> findPage(Boolean isEnabled, Boolean isExchange, Boolean hasExpired, Pageable pageable) {
        return couponDao.findPage(isEnabled, isExchange, hasExpired, pageable);
    }

    @Override
    public Set<Coupon> findReceivableCoupons(Member member) {
        // 获取针对所有会员的优惠券:(1)已经启用(2)未过期(3)不是微信分享
        List<Coupon> coupons = couponDao.findEnableCoupons();
        // 当前会员已经领取的优惠券码(优惠券)
        List<CouponCode> couponCodes = member.getCouponCodes();
        // 获取可领取的优惠券及其可领取的次数(Key:优惠券，value:优惠券的领取次数)
        HashMap<Coupon, Integer> receivableCoupons = new HashMap<>();
        for (Coupon coupon : coupons) {
            receivableCoupons.put(coupon, coupon.getReceivableNum());
        }
        for (CouponCode couponCode : couponCodes) {
            Coupon coupon = couponCode.getCoupon();
            Integer count = receivableCoupons.get(coupon);
            if (count == null) {
                continue;
            }
            --count;
            receivableCoupons.put(coupon, count);
            if (count <= 0) {
                receivableCoupons.remove(coupon);
            }
        }
        return receivableCoupons.keySet();
    }

    @Override
    public Long findReceivableCount4Coupon(Member member, Coupon coupon) {
        return couponDao.findReceivableCount4Coupon(member, coupon);
    }

    @Override
    public List<Coupon> findEnableCoupons() {
        return couponDao.findEnableCoupons();
    }

}